<template>
	<view class="DataMeasurement_container">
		<view v-if="!uploadSuccess && !notHasMeasure" class="waitSubmitSuccess">
			<view class="waitSubmitTitle">
				<text v-if="!isWaiting && !reportHasDown">请上传规范姿势的照片</text>
			</view>

			<view class="uploadPhotoBox">
				<!-- 坐姿照片上传 -->
				<view class="baseTitle">
					<text></text>坐姿
				</view>
				<view class="photoLine">
					<view class="photoBox">
						<view class="title">
							<text class="required">*</text>
							<text class="text">侧面坐姿抬手</text>
						</view>
						<u-upload
							ref="upload1"
							:fileList="photoList1"
							@afterRead="afterReadPhotoList1"
							@delete="deletePicPhotoList1"
							:previewFullImage="true"
							:showUpload="isNeedShow1"
							:deletable="isNeedShowDelete1"
							name="1"
							:maxCount="1"
							width="107"
							height="139"
						>
						<image src="@/static/dataMeasurement/1.png" mode="widthFix" style="width: 194rpx;height: 80px;"></image>
						</u-upload>
						<view @click="upload1" v-if="!photoList1.length" class="uploadText">
							<img src="@/static/dataMeasurement/cloud.png">
							<view>点击上传</view>
						</view>
					</view>
					<view class="photoBox">
						<view class="title">
							<text class="required">*</text>
							<text class="text">侧面坐姿抱胸</text>
						</view>
						<u-upload
							ref="upload2"
							:fileList="photoList2"
							@afterRead="afterReadPhotoList2"
							@delete="deletePicPhotoList2"
							:previewFullImage="true"
							:showUpload="isNeedShow2"
							:deletable="isNeedShowDelete2"
							name="1"
							:maxCount="1"
							width="107"
							height="139"
						>
						<image src="@/static/dataMeasurement/2.png" mode="widthFix" style="width: 194rpx;height: 80px;"></image>
						</u-upload>
						<view @click="upload2" v-if="!photoList2.length" class="uploadText">
							<img src="@/static/dataMeasurement/cloud.png">
							<view>点击上传</view>
						</view>
					</view>
				</view>

				<!-- 站姿照片上传 -->
				<view class="baseTitle">
					<text></text>站姿
				</view>
				<view class="photoLine">
					<view class="photoBox">
						<view class="title">
							<text class="required">*</text>
							<text class="text">侧面站姿抬手</text>
						</view>
						<u-upload
							ref="upload3"
							:fileList="photoList3"
							@afterRead="afterReadPhotoList3"
							@delete="deletePicPhotoList3"
							:previewFullImage="true"
							:showUpload="isNeedShow3"
							:deletable="isNeedShowDelete3"
							name="1"
							:maxCount="1"
							width="107"
							height="139"
						>
						<image src="@/static/dataMeasurement/3.png" mode="widthFix" style="width: 194rpx;height: 80px;"></image>
						</u-upload>
						<view @click="upload3" v-if="!photoList3.length" class="uploadText">
							<img src="@/static/dataMeasurement/cloud.png">
							<view>点击上传</view>
						</view>
					</view>
					<view class="photoBox">
						<view class="title">
							<text class="required">*</text>
							<text class="text">侧面站姿抱胸</text>
						</view>
						<u-upload
							ref="upload4"
							:fileList="photoList4"
							@afterRead="afterReadPhotoList4"
							@delete="deletePicPhotoList4"
							:previewFullImage="true"
							:showUpload="isNeedShow4"
							:deletable="isNeedShowDelete4"
							name="1"
							:maxCount="1"
							width="107"
							height="139"
						>
						<image src="@/static/dataMeasurement/4.png" mode="widthFix" style="width: 194rpx;height: 80px;"></image>
						</u-upload>
						<view @click="upload4" v-if="!photoList4.length" class="uploadText">
							<img src="@/static/dataMeasurement/cloud.png">
							<view>点击上传</view>
						</view>
					</view>
					<view class="photoBox">
						<view class="title">
							<text class="required">*</text>
							<text class="text">正面站姿</text>
						</view>
						<u-upload
							ref="upload5"
							:fileList="photoList5"
							@afterRead="afterReadPhotoList5"
							@delete="deletePicPhotoList5"
							:previewFullImage="true"
							:showUpload="isNeedShow5"
							:deletable="isNeedShowDelete5"
							name="1"
							:maxCount="1"
							width="107"
							height="139"
						>
						<image src="@/static/dataMeasurement/5.png" mode="widthFix" style="width: 194rpx;height: 80px;"></image>
						</u-upload>
						<view @click="upload5" v-if="!photoList5.length" class="uploadText">
							<img src="@/static/dataMeasurement/cloud.png">
							<view>点击上传</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 上传按钮 -->
			<u-button v-if="!isWaiting && !reportHasDown" @click="submit" text="确认上传" color="#016ab7" size="big" shape="circle" :customStyle="buttonStyle1"></u-button>

			<!-- 等待生成 -->
			<view v-if="isWaiting" class="waiting">
				<view class="uploadTime">上传时间: {{ uploadTime.year }}年{{ uploadTime.month }}月{{ uploadTime.day }}日</view>
				<view class="hourglass">
					<image src="@/static/dataMeasurement/hourglass.png" mode="widthFix" style="width: 100rpx;height: 100rpx;"></image>
					<view class="text">等待生成</view>
					<view class="tips">*预计上传后2个工作日可查看</view>
				</view>

				<!-- 修改照片按钮 -->
				<view @click="handleUploadAgain" class="reUploadButton">返回修改</view>
			</view>

			<!-- 已生成报告 -->
			<view v-if="reportHasDown" class="finish">
				<view class="iconBox">
					<image src="@/static/dataMeasurement/finish.png" mode="widthFix" style="width: 100rpx;height: 100rpx;"></image>
					<view class="text">已生成报告</view>
				</view>
				<u-button @click="lookPDF" text="查看报告" color="#016ab7" size="big" shape="circle" :customStyle="buttonStyle"></u-button>
				<!-- <u-button @click="downLoadPDF" text="下载报告" color="#61cdc5" size="big" shape="circle" :customStyle="buttonStyle1"></u-button> -->
			</view>
		</view>

		<!-- 上传成功显示 -->
		<view v-if="uploadSuccess" class="submitSuccess">
			<view class="iconBox">
				<image src="@/static/dataMeasurement/finish.png" mode="widthFix" style="width: 200rpx;height: 200rpx;"></image>
				<view class="text">上传成功</view>
				<view class="tips">*请等待2个工作日后查看报告</view>
			</view>
			<u-button @click="goHome" text="返回首页" color="#016ab7" size="big" shape="circle" :customStyle="buttonStyle"></u-button>
		</view>

		<!-- 还未测量没有生成报告时显示 -->
		<view v-if="notHasMeasure" class="notMeasure">
			<view class="iconBox">
				<image src="@/static/dataMeasurement/noneReport.png" mode="widthFix" style="width: 400rpx;height: 400rpx;"></image>
				<view class="text">无报告内容</view>
			</view>
			<u-button @click="goBaseInfo" text="先去测量" icon="edit-pen-fill" iconColor="#fff" color="#016ab7" size="big" shape="circle"  :customStyle="buttonStyle2"></u-button>
		</view>

		<!-- 是否修改照片重新上传弹窗 -->
		<u-modal :show="reUploadDialog" title="提示" :currentTitleStyle="currentTitleStyle" ref="uModal" class="reUploadDialog">
			<view class="slot-content" style="text-align: center; font-size: 28rpx;">
				<text>是否确认返回修改此报告图片</text>
			</view>
			<template slot="confirmButton" class="footer">
				<reUploadFooter @confirmReuploadDialog="confirmReuploadDialog" @closeReuploadDialog="closeReuploadDialog" />
			</template>
		</u-modal>
	</view>
</template>

<script>
	import { baseUrl, imgURL } from "@/utils/request"
	import { mapGetters } from "vuex";
	import reUploadFooter from "./components/reUploadFooter.vue";
	import { deleteImg, saveImg, updateImg, getReportStatus, getUserInfo} from "@/api/home.js";
	export default {
		components: {
			reUploadFooter,
		},
		data() {
			return {
				isNeedShow1: true,
				isNeedShow2: true,
				isNeedShow3: true,
				isNeedShow4: true,
				isNeedShow5: true,
				isNeedShowDelete1: true,
				isNeedShowDelete2: true,
				isNeedShowDelete3: true,
				isNeedShowDelete4: true,
				isNeedShowDelete5: true,
				photoList1: [],
				photoList2: [],
				photoList3: [],
				photoList4: [],
				photoList5: [],
				photo1Url: "",
				photo2Url: "",
				photo3Url: "",
				photo4Url: "",
				photo5Url: "",
				pdfUrl: "",
				preImgList: [],
				uploadTime: {
					year: "",
					month: "",
					day: ""
				},
				buttonStyle: {
					marginTop: "40rpx",
					width: "92%"
				},
				buttonStyle1: {
					marginBottom: "40rpx",
					width: "92%"
				},
				buttonStyle2: {
					marginTop: "200rpx",
					width: "92%"
				},
				currentTitleStyle: `padding: 20rpx 0;background-color: #ededed;color: #000`,
				uploadSuccess: false,
				notHasMeasure: false,
				isWaiting: false,
				reUploadDialog: false,
				reportHasDown: false,
				uploadId: '',
				mode: 'upload'
			};
		},
		computed: {
			...mapGetters(['userInfo'])
		},
		methods: {
			async submit() {
				// 判断是否都上传了
				let isAllUpload = this.isAllUpload();
				let memberUserUploadMeasureList = [
					{
						fieldId: '8',
						fieldName: '侧面坐姿抬手',
						fieldKey: 'sideSittingPostureHandUp',
						fieldValue: this.photo1Url,
					},
					{
						fieldId: '9',
						fieldName: '侧面坐姿抱胸',
						fieldKey: 'sideSittingPostureChest',
						fieldValue: this.photo2Url,
					},
					{
						fieldId: '10',
						fieldName: '侧面站姿抬手',
						fieldKey: 'sideStandPostureHandUp',
						fieldValue: this.photo3Url,
					},
					{
						fieldId: '11',
						fieldName: '侧面站姿抱胸',
						fieldKey: 'sideStandPostureChest',
						fieldValue: this.photo4Url,
					},
					{
						fieldId: '12',
						fieldName: '正面站姿',
						fieldKey: 'frontStandPosture',
						fieldValue: this.photo5Url,
					},
				];
				if (isAllUpload && this.mode == 'upload') {
					let res = await saveImg({ memberUserUploadMeasureList })
					if (res.code == 1) {
						this.uploadSuccess = true;
					} else {
						uni.showToast({
							title: res.message,
							icon: 'error',
							duration: 2000
						});
					}
				} else if (isAllUpload && this.mode == 'reUpload') {
					let res = await updateImg({ memberUserUploadMeasureList }, this.uploadId)
					if (res.code == 1) {
						this.uploadSuccess = true;
					} else {
						uni.showToast({
							title: res.message,
							icon: 'error',
							duration: 2000
						});
					}
				}
			},
			handleUploadAgain() {
				this.reUploadDialog = true;
			},
			confirmReuploadDialog() {
				this.isNeedShowDelete1 = true;
				this.isNeedShowDelete2 = true;
				this.isNeedShowDelete3 = true;
				this.isNeedShowDelete4 = true;
				this.isNeedShowDelete5 = true;
				this.isNeedShow1 = true;
				this.isNeedShow2 = true;
				this.isNeedShow3 = true;
				this.isNeedShow4 = true;
				this.isNeedShow5 = true;
				this.reUploadDialog = false;
				this.isWaiting = false;

				this.mode = 'reUpload';
			},
			closeReuploadDialog() {
				this.reUploadDialog = false;
			},
			async afterReadPhotoList1(e) {
				let result = await this.uploadFilePromise(e);
				console.log(result);
				this.photo1Url = result.data[0];
				this.photoList1 = [{
					url: imgURL + result.data[0]
				}];
			},
			async deletePicPhotoList1(e) {
				// let result = await this.deleteImg(this.photo1Url);
				// if (result.code == 1) {
				// 	this.photoList1.splice(e.index, 1);
				// }

				this.photoList1.splice(e.index, 1);
			},
			async afterReadPhotoList2(e) {
				let result = await this.uploadFilePromise(e);
				console.log(result);
				this.photo2Url = result.data[0];
				this.photoList2 = [{
					url: imgURL + result.data[0]
				}];
			},
			async deletePicPhotoList2(e) {
				// let result = await this.deleteImg(this.photo2Url);
				// if (result.code == 1) {
				// 	this.photoList2.splice(e.index, 1);
				// }
				
				this.photoList2.splice(e.index, 1);
			},
			async afterReadPhotoList3(e) {
				let result = await this.uploadFilePromise(e);
				console.log(result);
				this.photo3Url = result.data[0];
				this.photoList3 = [{
					url: imgURL + result.data[0]
				}];
			},
			async deletePicPhotoList3(e) {
				// let result = await this.deleteImg(this.photo3Url);
				// if (result.code == 1) {
				// 	this.photoList3.splice(e.index, 1);
				// }

				this.photoList3.splice(e.index, 1);
			},
			async afterReadPhotoList4(e) {
				let result = await this.uploadFilePromise(e);
				console.log(result);
				this.photo4Url = result.data[0];
				this.photoList4 = [{
					url: imgURL + result.data[0]
				}];
			},
			async deletePicPhotoList4(e) {
				// let result = await this.deleteImg(this.photo4Url);
				// if (result.code == 1) {
				// 	this.photoList4.splice(e.index, 1);
				// }

				this.photoList4.splice(e.index, 1);
			},
			async afterReadPhotoList5(e) {
				let result = await this.uploadFilePromise(e);
				console.log(result);
				this.photo5Url = result.data[0];
				this.photoList5 = [{
					url: imgURL + result.data[0]
				}];
			},
			async deletePicPhotoList5(e) {
				// let result = await this.deleteImg(this.photo5Url);
				// if (result.code == 1) {
				// 	this.photoList5.splice(e.index, 1);
				// }

				this.photoList5.splice(e.index, 1);
			},
			upload1() {
				this.$refs.upload1.chooseFile();
			},
			upload2() {
				this.$refs.upload2.chooseFile();
			},
			upload3() {
				this.$refs.upload3.chooseFile();
			},
			upload4() {
				this.$refs.upload4.chooseFile();
			},
			upload5() {
				this.$refs.upload5.chooseFile();
			},
			uploadFilePromise(e) {
				console.log(e);
				let header = {
					"Content-Type": "multipart/form-data",
				};
				header[this.userInfo.tokenName] = this.userInfo.tokenValue;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: `${baseUrl}/app/memberUserUpload/multiFile`,
						filePath: e.file.url,
						name: "files",
						header,
						success: (res) => {
							resolve(JSON.parse(res.data));
						},
						fail: (err) => {
							reject(err);
						},
					});
				});
			},
			deleteImg(path) {
				return new Promise((resolve, reject) => {
					deleteImg({ filePath: path }).then((res) => {
						resolve(res);
					}).catch((err) => {
						reject(err);
					});
				});
			},
			isAllUpload() {
				let img1 = this.photoList1.length > 0 ? true : false;
				let img2 = this.photoList2.length > 0 ? true : false;
				let img3 = this.photoList3.length > 0 ? true : false;
				let img4 = this.photoList4.length > 0 ? true : false;
				let img5 = this.photoList5.length > 0 ? true : false;

				if (img1 && img2 && img3 && img4 && img5) {
					return true;
				} else {
					uni.showToast({
						title: "请将照片上传完整",
						icon: "none",
					});
					return false;
				}
			},
			goHome() {
				uni.switchTab({
					url: "/pages/home/home",
				});
			},
			goBaseInfo() {
				uni.redirectTo({
					url: "/subPages/baseInfo/baseInfo",
				});
			},
			lookPDF() {
				// uni.showLoading({
				// 	title: '打开中,请稍等...',
				// });
				// uni.downloadFile({
				// 	url: this.pdfUrl,
				// 	success: function (res) {
				// 		console.log(res);
				// 		var filePath = res.tempFilePath;
				// 		uni.hideLoading();
				// 		uni.openDocument({
				// 			filePath: filePath,
				// 			showMenu: true,
				// 			success: function (res) {
				// 				console.log('打开文档成功');
				// 			}
				// 		});
				// 	}
				// });
				
				uni.navigateTo({
					url: `/subPages/lookPreImg/lookPreImg?img1Url=${this.preImgList[0]}&img2Url=${this.preImgList[1]}`,
				})
			},
			downLoadPDF() {
				uni.showLoading({
					title: '下载中,请稍等...',
				});
				const fs = wx.getFileSystemManager();
				uni.downloadFile({
					url: this.pdfUrl,
					success: function (res) {
						console.log(res);
						var filePath = res.tempFilePath;
						fs.saveFile({
							tempFilePath: filePath,
							filePath: wx.env.USER_DATA_PATH + '/test.pdf',
							success: function (res) {
								console.log(res);
								uni.hideLoading();
								const savedFilePath = res.savedFilePath;
								uni.showToast({
									title: "下载成功,请将文件分享给文件传输助手",
									icon: "none",
								});

								setTimeout(() => {
									uni.openDocument({
										filePath: savedFilePath,
										showMenu: true,
										success: function (res) {
											console.log(res,'打开文档成功');
										}
									});
								}, 1500);
							},
							fail: function (err) {
								console.log(err);
								uni.showToast({
									title: "下载失败",
									icon: "none",
								});
							}
						})
					}
				});
			},
			async getReportStatus() {
				// 获取报告状态信息
				let Report = await getReportStatus();
				// 获取用户资料信息
				let userInfo = await getUserInfo();

				// 如果报告的data为空，并且用户信息的data为空，说明还没有上传基本信息，需要先上传基本信息
				if (Report.code == 1 && userInfo.code == 1) {
					if (!Report.data.length && !userInfo.data.isCompleted) {
						this.notHasMeasure = true;
						return;
					}
				}

				if (Report.code == 1 && Report.data.length) {
					// 上传记录id保存
					this.uploadId = Report.data[0].id;

					// 上传时间
					this.uploadTime.year = Report.data[0].gmtCreate?.slice(0,4)
					this.uploadTime.month = Report.data[0].gmtCreate?.slice(5,7)
					this.uploadTime.day = Report.data[0].gmtCreate?.slice(8,10)

					// 上传照片回显
					Report.data[0].memberUserUploadMeasureList.forEach(item => {
						if (item.fieldKey == 'sideSittingPostureHandUp') {
							this.photoList1 = [{
								url: imgURL + item.fieldValue
							}];
							this.photo1Url = item.fieldValue
							this.isNeedShow1 = false;
							this.isNeedShowDelete1 = false;
						}
						if (item.fieldKey == 'sideSittingPostureChest') {
							this.photoList2 = [{
								url: imgURL + item.fieldValue
							}];
							this.photo2Url = item.fieldValue
							this.isNeedShow2 = false;
							this.isNeedShowDelete2 = false;
						}
						if (item.fieldKey == 'sideStandPostureHandUp') {
							this.photoList3 = [{
								url: imgURL + item.fieldValue
							}];
							this.photo3Url = item.fieldValue
							this.isNeedShow3 = false;
							this.isNeedShowDelete3 = false;
						}
						if (item.fieldKey == 'sideStandPostureChest') {
							this.photoList4 = [{
								url: imgURL + item.fieldValue
							}];
							this.photo4Url = item.fieldValue
							this.isNeedShow4 = false;
							this.isNeedShowDelete4 = false;
						}
						if (item.fieldKey == 'frontStandPosture') {
							this.photoList5 = [{
								url: imgURL + item.fieldValue
							}];
							this.photo5Url = item.fieldValue
							this.isNeedShow5 = false;
							this.isNeedShowDelete5 = false;
						}
					})

					// 报告状态判断
					if (Report.data[0].measureStatus == 0 || Report.data[0].measureStatus == 1) {
						this.isWaiting = true;
					} else if (Report.data[0].measureStatus == 2) {
						this.reportHasDown = true;
						// this.pdfUrl = imgURL + Report.data[0].resultUrl;
						console.log('获取到的预览图片地址:', Report.data[0].resultUrl);
						let preImgList = Report.data[0].resultUrl.split(',')
						preImgList.forEach(item => {
							this.preImgList.push(imgURL + item)
						})
					}
				}
			},
		},
		onLoad() {
			this.getReportStatus();
		},
	}
</script>

<style lang="scss">
.DataMeasurement_container {
	background-color: #f2f2f2;

	.waitSubmitSuccess {

		.waitSubmitTitle {
			color: #fff;
			height: 150rpx;
			font-size: 36rpx;
			font-weight: 800;
			padding: 30rpx 50rpx;
			background-color: #016ab7;
		}

		.baseTitle {
			padding: 30rpx 0;
			font-weight: 700;

			text {
				position: relative;
				top: 5.5rpx;
				display: inline-block;
				width: 10rpx;
				height: 32rpx;
				background-color: #016ab7;
				border-radius: 4rpx;
				margin-right: 10rpx;
			}
		}

		.uploadPhotoBox {
			position: relative;
			top: -100rpx;
			left: 30rpx;
			width: 92%;
			border-radius: 20rpx;
			background-color: #fff;

			.baseTitle {
				padding: 30rpx 20rpx;
			}

			.photoLine {
				display: flex;
				// justify-content: center;
				align-items: center;
				padding: 0 20rpx;

				&:last-child {
					justify-content: space-between;
				}

				.photoBox {
					width: 30%;
					height: 400rpx;
					// background-color: #016ab7;
					margin-right: 30rpx;
					margin-bottom: 30rpx;

					&:last-child {
						margin-right: 0;
					}

					.title {
						text-align: center;
						margin-bottom: 20rpx;

						.required {
							color: red;
						}

						.text {
							font-size: 28rpx;
						}
					}

					.uploadText {
						display: flex;
						justify-content: center;
						align-items: center;
						color: #016ab7;
						font-size: 28rpx;
						margin-top: 20rpx;

						img {
							display: block;
							width: 40rpx;
							height: 40rpx;
						}
					}
				}
			}
		}
		
		.waiting {
			position: relative;
			top: -50rpx;
			left: 30rpx;
			width: 92%;
			border-radius: 20rpx;
			padding: 30rpx 0;
			background-color: #fff;

			.uploadTime {
				color: #ccc;
				font-size: 28rpx;
				text-align: center;
				margin: 20rpx 0;
			}

			.hourglass {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.text {
					font-size: 28rpx;
					margin: 20rpx 0;
				}

				.tips {
					color: #0173bc;
					font-size: 28rpx;
				}
			}

			.reUploadButton {
				color: #016ab7;
				text-align: center;
				margin-top: 40rpx;
				text-decoration: underline;
			}
		}

		.finish {
			position: relative;
			top: -50rpx;
			left: 30rpx;
			width: 92%;
			border-radius: 20rpx;
			padding: 30rpx 0;
			background-color: #fff;

			.iconBox {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				.text {
					color: #016ab7;
					font-size: 28rpx;
					margin: 20rpx 0;
				}
			}
		}
	}

	.submitSuccess {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-color: #fff;

		.iconBox {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 100%;

			.text {
				color: #016ab7;
				font-size: 38rpx;
				margin: 20rpx 0;
			}

			.tips {
				color: #ccc;
				font-size: 32rpx;
				margin-bottom: 20rpx;
			}
		}
	}

	.notMeasure {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		height: 100vh;
		background-color: #fff;

		.iconBox {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			width: 100%;

			.text {
				color: #ccc;
				font-size: 28rpx;
				margin: 20rpx 0;
			}
		}
	}
}
</style>
